var M69 = function( id, tileSize ) {

	var MAP = 1;

	this.setMap = function( mapM69 ) {
		this.mapM69_ = mapM69;
	};

	this.getMap = function() {
		return this.mapM69_;
	};

	this.setMiner = function( miner ) {
		this.miner_ = miner;
	};

	this.getMiner = function() {
		return this.miner_;
	};

	this.setMapDiff = function( mapDiff ) {
		this.mapDiff_ = mapDiff;
	};

	this.getMapDiff = function() {
		return this.mapDiff_;
	};

	// events

	this.mapClick = function( pos ) {
		pos.x -= this.getMap().getTablePosition().x;
		pos.y -= this.getMap().getTablePosition().y;

		this.getMiner().getBrain().goal( pos );
	};

	this.setMode = function( mode ) {
		this.mode_ = mode;
		if ( MAP == this.mode_ ) {
			Timer.removeTask( this );
			Timer.addTask( this );
		}
	};

	this.getMode = function() {
		return this.mode_;
	};

	this.run = function( t ) {

		this.getMiner().getBrain().run( t );

		var minerTile = this.getMiner().getSprite().getPosition().clone().toTile( this.getMap().getTileSize() );
		if ( this.getMap().getExit().equals( minerTile ) ) {
			//:Util.log( 'exit reached '  + minerTile + ' and ' + this.getMap().getExit() );
			this.newBoard();
		}

		return true;
	};

	this.newBoard = function() {
		// TODO: save olde map and do some cool transition...
		this.getMap().randomBoard();
		this.getMiner().getBrain().clear();
		var start = this.getMap().startXY();
		this.getMiner().getSprite().moveTo( start.x, start.y );
	};

	//M69_sprites
	this.addSprite = function() {
		var id = 'sprite_' + Util.nextId();
		Util.id( 'M69_sprites' ).appendChild(
			Util.newNode( 'div', {id:id} )
		);
		return id;
	};

	this.removeSprite = function( sprite ) {
		Util.id( 'M69_sprites' ).removeChild( sprite.getNode() );
	};

	this.init = function( id ) {
		Timer.delay = 50;
		var table = GuiM69.makeTabs( Util.id( id ), tileSize );
		this.setMap( new MapM69( table, tileSize ) );


		this.setMiner( new Miner69( this.addSprite(), this.getMap() ) );
		//this.setMiner( new Miner69( 'M69_miner', this.getMap() ) );
		//PathBrainBuddy.brain( this.getMiner() );
		PathBrain.brain( this.getMiner() );

		this.newBoard();

		var thiz = this;
		table.onclick = function( e ) { thiz.mapClick( MouseUtil.getMouseXY( e ) ); };

		this.setMode( MAP );
	};

	this.init( id, tileSize );
};
